package cn.lxq.week01.testmysel;

import java.lang.reflect.Field;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;

public class PrintJvmClassLoaderPath {
	public static void main(String[]args) {
		URL[]urls = sun.misc.Launcher.getBootstrapClassPath().getURLs();
		System.out.println("BootStrapClassPath==>");
		for(URL url:urls) {
			System.out.println(url.toExternalForm());
		}
		printClassLoader("ExtClassLoader",PrintJvmClassLoaderPath.class.getClassLoader().getParent());
		printClassLoader("AppClassLoader",PrintJvmClassLoaderPath.class.getClassLoader());

	}
	
	public static void printClassLoader(String name, ClassLoader cl) {
		System.out.println(name+"==>"+cl.toString());
		printUrl(cl);
	}
	
	public static void printUrl(ClassLoader cl) {
		Object ucp = getField(cl,"ucp");
		Object path = getField(ucp,"path");
		if(null==path) {
			return;
		}
		ArrayList<URL> ps = (ArrayList)path;
		for(URL p:ps) {
			System.out.println(p.toExternalForm());
		}
	}
	
	public static Object getField(Object obj, String field) {
		Field f=null;
		try {
			if(obj instanceof URLClassLoader) {
				f=URLClassLoader.class.getDeclaredField(field);
			}else {
				f = obj.getClass().getDeclaredField(field);
			}
			f.setAccessible(true);
			return f.get(obj);
		} catch (NoSuchFieldException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}
}
